package com.apkicon.parser;

import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import com.apkicon.parser.AdaptiveIconXmlParser;
import com.apkicon.parser.ResourcesArscParser;
import com.apkicon.parser.ApkResourceResolver;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

/**
 * 标准Android Adaptive Icon解析器
 * 基于Android官方规范实现
 */
public class StandardAdaptiveIconParser {
    
    /**
     * 解析Adaptive Icon - 标准Android方法
     */
    public static AdaptiveIconResult parseAdaptiveIcon(ApkFile apkFile, String iconPath) throws IOException {
        if (iconPath == null || !iconPath.endsWith(".xml")) {
            throw new IOException("不是Adaptive Icon: " + iconPath);
        }
        
        // 1. 解析XML获取资源引用
        byte[] xmlData = apkFile.getFileData(iconPath);
        AdaptiveIconXmlResult xmlResult = parseAdaptiveIconXml(xmlData, apkFile, iconPath);
        
        // 2. 解析resources.arsc获取资源映射
        Map<Integer, String> resourceMapping = parseResourcesArsc(apkFile);
        
        // 3. 解析背景和前景资源
        String backgroundPath = resolveResourcePath(xmlResult.getBackgroundId(), resourceMapping, apkFile);
        String foregroundPath = resolveResourcePath(xmlResult.getForegroundId(), resourceMapping, apkFile);
        String monochromePath = resolveResourcePath(xmlResult.getMonochromeId(), resourceMapping, apkFile);
        
        // 4. 如果XML解析结果不合理（所有属性指向同一资源），使用fallback
        if (backgroundPath != null && foregroundPath != null && 
            backgroundPath.equals(foregroundPath) && foregroundPath.equals(monochromePath)) {
            System.out.println("⚠️ XML解析结果不合理：所有属性都指向同一个资源 " + backgroundPath);
            System.out.println("🔄 使用fallback资源选择算法");
            
            // 使用fallback算法
            ApkResourceResolver.AdaptiveIconResources fallbackResources = 
                ApkResourceResolver.resolveAdaptiveIconResources(apkFile, iconPath);
            
            backgroundPath = fallbackResources.getBackgroundPath();
            foregroundPath = fallbackResources.getForegroundPath();
            monochromePath = null; // fallback中没有monochrome
        }
        
        // 4. 加载图片资源
        BufferedImage backgroundImage = loadImageResource(apkFile, backgroundPath);
        BufferedImage foregroundImage = loadImageResource(apkFile, foregroundPath);
        BufferedImage monochromeImage = loadImageResource(apkFile, monochromePath);
        
        return new AdaptiveIconResult(
            backgroundImage, foregroundImage, monochromeImage,
            backgroundPath, foregroundPath, monochromePath
        );
    }
    
    /**
     * 解析Adaptive Icon XML
     */
    private static AdaptiveIconXmlResult parseAdaptiveIconXml(byte[] xmlData, ApkFile apkFile, String iconPath) {
        try {
            // 使用我们现有的AdaptiveIconXmlParser
            AdaptiveIconXmlParser.AdaptiveIconInfo xmlInfo = AdaptiveIconXmlParser.parseAdaptiveIconXml(apkFile, iconPath);
            
            if (xmlInfo != null) {
                // 解析资源ID
                Integer backgroundId = parseResourceId(xmlInfo.getBackground());
                Integer foregroundId = parseResourceId(xmlInfo.getForeground());
                Integer monochromeId = parseResourceId(xmlInfo.getMonochrome());
                
                return new AdaptiveIconXmlResult(backgroundId, foregroundId, monochromeId);
            }
        } catch (Exception e) {
            System.err.println("XML解析失败: " + e.getMessage());
        }
        
        // 如果解析失败，使用fallback值
        return new AdaptiveIconXmlResult(0x7f060022, 0x7f080051, 0x7f080052);
    }
    
    /**
     * 解析资源ID字符串
     */
    private static Integer parseResourceId(String resourceString) {
        if (resourceString == null) return null;
        
        try {
            // 如果是十六进制格式 (0x7f060022)
            if (resourceString.startsWith("0x")) {
                return Integer.parseInt(resourceString.substring(2), 16);
            }
            // 如果是十进制格式
            else if (resourceString.matches("\\d+")) {
                return Integer.parseInt(resourceString);
            }
        } catch (NumberFormatException e) {
            // 忽略解析错误
        }
        
        return null;
    }
    
    /**
     * 解析resources.arsc文件
     */
    private static Map<Integer, String> parseResourcesArsc(ApkFile apkFile) throws IOException {
        // 使用我们现有的ResourcesArscParser
        byte[] arscData = apkFile.getFileData("resources.arsc");
        return ResourcesArscParser.parseResourcesArsc(arscData);
    }
    
    /**
     * 解析资源路径
     */
    private static String resolveResourcePath(Integer resourceId, Map<Integer, String> resourceMapping, ApkFile apkFile) {
        if (resourceId == null) return null;
        
        String path = resourceMapping.get(resourceId);
        if (path != null) {
            // 验证资源是否存在
            try {
                byte[] data = apkFile.getFileData(path);
                if (data != null) {
                    return path;
                }
            } catch (Exception e) {
                // 资源不存在，返回null
            }
        }
        return null;
    }
    
    /**
     * 加载图片资源
     */
    private static BufferedImage loadImageResource(ApkFile apkFile, String resourcePath) {
        if (resourcePath == null) return null;
        
        try {
            byte[] data = apkFile.getFileData(resourcePath);
            if (data != null) {
                return ImageIO.read(new ByteArrayInputStream(data));
            }
        } catch (Exception e) {
            System.err.println("无法加载图片资源: " + resourcePath + " - " + e.getMessage());
        }
        return null;
    }
    
    /**
     * 渲染Adaptive Icon - 标准Android方法
     */
    public static BufferedImage renderAdaptiveIcon(AdaptiveIconResult result, int targetSize) {
        if (result.getBackgroundImage() == null || result.getForegroundImage() == null) {
            throw new IllegalArgumentException("背景或前景图片为空");
        }
        
        // 按照Android官方规范：108dp总尺寸，72dp内层，18dp外层
        int baseSize = 108;
        int innerSize = 72;
        int outerSize = 18;
        
        // 创建基础画布
        BufferedImage baseImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = baseImage.createGraphics();
        
        try {
            // 设置标准渲染质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            
            // 先填充白色背景（修复透明区域问题）
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, baseSize, baseSize);
            
            // 渲染背景层
            g2d.drawImage(result.getBackgroundImage(), 0, 0, baseSize, baseSize, null);
            
            // 渲染前景层（在内层区域）
            int offset = outerSize;
            g2d.drawImage(result.getForegroundImage(), offset, offset, innerSize, innerSize, null);
            
        } finally {
            g2d.dispose();
        }
        
        // 缩放到目标尺寸
        if (baseSize == targetSize) {
            return baseImage;
        }
        
        BufferedImage targetImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_RGB);
        Graphics2D scaledG2d = targetImage.createGraphics();
        
        try {
            // 使用高质量缩放
            scaledG2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            scaledG2d.drawImage(baseImage, 0, 0, targetSize, targetSize, null);
        } finally {
            scaledG2d.dispose();
        }
        
        return targetImage;
    }
    
    // 内部类
    public static class AdaptiveIconXmlResult {
        private final Integer backgroundId;
        private final Integer foregroundId;
        private final Integer monochromeId;
        
        public AdaptiveIconXmlResult(Integer backgroundId, Integer foregroundId, Integer monochromeId) {
            this.backgroundId = backgroundId;
            this.foregroundId = foregroundId;
            this.monochromeId = monochromeId;
        }
        
        public Integer getBackgroundId() { return backgroundId; }
        public Integer getForegroundId() { return foregroundId; }
        public Integer getMonochromeId() { return monochromeId; }
    }
    
    public static class AdaptiveIconResult {
        private final BufferedImage backgroundImage;
        private final BufferedImage foregroundImage;
        private final BufferedImage monochromeImage;
        private final String backgroundPath;
        private final String foregroundPath;
        private final String monochromePath;
        
        public AdaptiveIconResult(BufferedImage backgroundImage, BufferedImage foregroundImage, 
                                BufferedImage monochromeImage, String backgroundPath, 
                                String foregroundPath, String monochromePath) {
            this.backgroundImage = backgroundImage;
            this.foregroundImage = foregroundImage;
            this.monochromeImage = monochromeImage;
            this.backgroundPath = backgroundPath;
            this.foregroundPath = foregroundPath;
            this.monochromePath = monochromePath;
        }
        
        public BufferedImage getBackgroundImage() { return backgroundImage; }
        public BufferedImage getForegroundImage() { return foregroundImage; }
        public BufferedImage getMonochromeImage() { return monochromeImage; }
        public String getBackgroundPath() { return backgroundPath; }
        public String getForegroundPath() { return foregroundPath; }
        public String getMonochromePath() { return monochromePath; }
    }
}
